#include "event_socket.h"

#define SERVER_PORT 666
#define SERVER_IP   "10.10.10.10"

extern unsigned char motion;

void event_socket_init(void)
{
  int sockfd;
  int len;
  struct sockaddr_in client_addr;
  char buf[64];
  memset(buf, 0, 8);

  /* TPv4协议  TCP协议 */
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  
  if( sockfd == -1 ){
    printf("sockfd error! reason: %s\n",strerror(errno));
    exit(1);
  }
  // bzero(&client_addr, sizeof(struct sockaddr_in));
  memset(&client_addr, '\0', sizeof(struct sockaddr_in));

  client_addr.sin_family = AF_INET;
  /* 将IP地址 从机器语言格式转换为IPV4网络格式 */
  inet_pton(AF_INET, SERVER_IP, &client_addr.sin_addr);
  client_addr.sin_port = htons(SERVER_PORT);

  printf("Ready to connect...\n");

  int ret = connect(sockfd, (struct sockaddr *)&client_addr, sizeof(client_addr));

  if( ret == 0 ){
    printf("Connect success!\n");
  }
  if( ret == -1 ){
    printf("connect error! reason: %s\n",strerror(errno));
    close(sockfd);
    exit(-1);
  }
  int data;
  while(1){    

    len = read(sockfd, buf, 8);
    
    if( len > 0 ){
    	// printf("%c %c %c\n",buf[0],buf[1],buf[2]);
      switch (buf[2])
      {
      case '3': motion = 0x3;
        /* code */
        break;
      case '5': motion = 0x5;
        /* code */
        break;
      case '8': motion = 0x8;
        /* code */
        break;
      case '6': motion = 0x6;
        /* code */
        break;
      case '0': motion = 0x0;
        /* code */
        break;
      }
    }
    printf("receive:%s\n",buf);
    // printf("%d\n",motion);
    // usleep(100*1000);
  }
  close(sockfd);
  
}
